package com.coachtam.ljgcapi.consumer;

import org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

/**
 * @Copyright (C), 2018-2020
 * @Author: JAVA在召唤
 * @Date: 2020-08-05 06:48
 * @Description:
 */
//@Component
public class RatelimiterConsumer implements Consumer<RequestRateLimiterGatewayFilterFactory.Config> {

    @Override
    public void accept(RequestRateLimiterGatewayFilterFactory.Config config) {
        config.setKeyResolver(hostAddrKeyResolver());
        config.setRateLimiter(new RedisRateLimiter(1,3));
    }
//    @Bean
//    public RateLimiter inMemoryRateLimiter(){
//        return new InMemoryRateLimiter();
//    }

//    @Bean(name = IpAddressKeyResolver.BEAN_NAME)
//    public KeyResolver ipAddressKeyResolver() {
//        return new IpAddressKeyResolver();
//    }

    @Bean
    public KeyResolver hostAddrKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }

//    @Bean
//    public KeyResolver userKeyResolver() {
//        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
//    }
//
//    @Bean
//    public KeyResolver apiKeyResolver() {
//        return exchange -> Mono.just(exchange.getRequest().getPath().value());
//    }
}
